package com.qq5194102.simpleskills.core;

import com.qq5194102.simpleskills.model.ExPlayerData;
import com.qq5194102.simpleskills.model.SwordPlayerData;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;

/**
 * Created by 5194102 on 2025/7/13.
 *  玩家数据管理器  (简单单例模式 主类onEnable中创建 赋值此处获取静态对象)
 */
public class PlayerDataManager implements Listener {
    private static PlayerDataManager playerDataManager;
    private final JavaPlugin plugin;
    private final File playerDataFolder;
    public static Map<String, ExPlayerData> globalPlayerData = new HashMap<>();
    public static final String PLAYER_DATA_FOLDER = "playerdata";
    private int saveInterval = 300; // 默认保存间隔（秒）
    private BukkitTask autoSaveTask;
    /**
     * 构造函数
     * 启动时调用 ： 初始化玩家数据文件夹
     * @param plugin 插件
     */
    public PlayerDataManager(JavaPlugin plugin) {
        this.plugin = plugin;
        this.playerDataFolder = new File(this.plugin.getDataFolder(), PLAYER_DATA_FOLDER);
        if (!playerDataFolder.exists()) {
            if (!playerDataFolder.mkdirs()){
                plugin.getLogger().log(Level.WARNING,"创建玩家文件夹失败");
            }
        }
        // 加载配置
        loadConfig();

        // 启动自动保存任务
        startAutoSave();
        PlayerDataManager.playerDataManager = this;
    }

    /**
     * 加载config配置
     */
    private void loadConfig() {
        // 检查配置文件是否存在
        if (plugin.getConfig().contains("auto-save-interval")) {
            saveInterval = plugin.getConfig().getInt("auto-save-interval", 300);
        } else {
            // 设置默认值
            plugin.getConfig().set("auto-save-interval", 300);
            plugin.saveConfig();
        }
        plugin.getLogger().info("Auto-save interval set to " + saveInterval + " seconds");
    }

    /**
     * 玩家加入时：加载该玩家数据
     */
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        Player player = event.getPlayer();
        ExPlayerData playerData = loadOrCreatePlayerData(player.getUniqueId());
        // 将playerData存储到玩家上下文globalPlayerData中
        globalPlayerData.put(player.getUniqueId().toString(), playerData);
    }
    /**
     * 玩家退出时：立即保存并移除缓存
     */
    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        Player player = event.getPlayer();
        UUID playerId = player.getUniqueId();

        // 立即保存玩家数据
        savePlayerData(playerId);

        // 从缓存中移除（可选，取决于内存管理策略）
        removePlayerData(playerId);
    }

    /**
     * 加载玩家数据
     * @param playerId 玩家ID
     * @return 玩家聚合技能数据
     */
    public ExPlayerData loadOrCreatePlayerData(UUID playerId) {
        File playerFile = getPlayerFile(playerId);
        // 文件不存在则创建新数据
        if (!playerFile.exists()) {
            ExPlayerData newData = createDefaultPlayerData();
            savePlayerData(playerId, newData);
            return newData;
        }
        return loadPlayerData(playerFile);
    }
    /**
     * 创建初始的玩家数据
     * @return 默认的玩家数据
     */
    private ExPlayerData createDefaultPlayerData() {
        ExPlayerData data = new ExPlayerData();

        data.setSwordSkillData(new SwordPlayerData());
        // 添加其他默认技能

        return data;
    }

    /**
     * 加载玩家数据
     * @param playerFile 玩家数据文件
     * @return 玩家聚合技能数据
     */
    private ExPlayerData loadPlayerData(File playerFile) {
        YamlConfiguration config = YamlConfiguration.loadConfiguration(playerFile);
        ExPlayerData data = new ExPlayerData();

        // 加载剑术数据
        if (config.contains("sword")) {
            SwordPlayerData sword = new SwordPlayerData();
            sword.setExperience(config.getInt("sword.experience"));
            data.setSwordSkillData(sword);
        } else {
            data.setSwordSkillData(new SwordPlayerData());
        }

        // 加载其他技能...

        return data;
    }

    /**
     * 把player数据保存到yml
     * @param playerId 玩家ID
     */
    public void savePlayerData(UUID playerId, ExPlayerData data) {
        File playerFile = getPlayerFile(playerId);
        YamlConfiguration config = new YamlConfiguration();

        // 保存剑术数据
        SwordPlayerData sword = data.getSwordSkillData();
        if (sword != null) {
            config.set("sword.experience", sword.getExperience());
        }

        // 保存其他技能...
        try {
            config.save(playerFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void savePlayerData(UUID playerId) {
        this.savePlayerData(playerId, globalPlayerData.get(playerId.toString()));
    }


    /**
     * 获取玩家数据文件
     * @param playerId 玩家ID
     * @return 玩家数据文件
     */
    private File getPlayerFile(UUID playerId) {
        return new File(playerDataFolder, playerId.toString() + ".yml");
    }

    public static ExPlayerData getPlayerData(UUID playerId) {
        return globalPlayerData.get(playerId.toString());
    }
    public static ExPlayerData setPlayerData(UUID playerId, ExPlayerData data) {
        return globalPlayerData.put(playerId.toString(), data);
    }
    public static ExPlayerData removePlayerData(UUID playerId) {
        return globalPlayerData.remove(playerId.toString());
    }
    public static Map<String, ExPlayerData> getGlobalPlayerData(){
        return globalPlayerData;
    }

    /**
     * 保存缓存中的所有玩家数据
     */
    private void saveCachedPlayerData() {
        for (Map.Entry<String, ExPlayerData> entry : globalPlayerData.entrySet()) {
            UUID playerId = UUID.fromString(entry.getKey());
            savePlayerData(playerId);
        }
    }
    /**
     * 启一个定时任务 定时保存玩家数据到配置文件
     */
    private void startAutoSave() {
        // 取消现有任务（如果存在）
        if (autoSaveTask != null && !autoSaveTask.isCancelled()) {
            autoSaveTask.cancel();
        }

        // 转换秒为tick（20 tick = 1秒）
        long ticks = saveInterval * 20L;

        // 创建并启动新的定时任务
        autoSaveTask = Bukkit.getScheduler().runTaskTimer(plugin, () -> {
            plugin.getLogger().info("Auto-saving player data...");
            saveCachedPlayerData();
            plugin.getLogger().info("Player data saved successfully");
        }, ticks, ticks); // 延迟ticks后执行，每隔ticks重复执行
    }

    /**
     * 重载保存间隔配置
     */
    public void reloadSaveInterval() {
        saveInterval = plugin.getConfig().getInt("auto-save-interval", 300);
        startAutoSave();
        plugin.getLogger().info("重载自动保存时间: " + saveInterval + " 秒");
    }

    /**
     * 插件禁用时保存所有玩家数据
     */
    public void onDisable() {
        // 保存所有玩家数据
        plugin.getLogger().info("保存所有玩家数据...");
        saveCachedPlayerData();
        // 取消自动保存任务
        if (autoSaveTask != null) {
            autoSaveTask.cancel();
        }
    }

    /**
     * 获取PlayerDataManager实例
     * @return PlayerDataManager实例
     */
    public static PlayerDataManager getPlayerDataManager(){
        if (playerDataManager==null) {
            throw new NullPointerException("PlayerDataManager is null");
        }else{
            return playerDataManager;
        }
    }
}
